package com.yzdmw.toutiao.detailsPage;

import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;

import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.BaseExpandableListAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.material.bottomsheet.BottomSheetBehavior;
import com.google.android.material.bottomsheet.BottomSheetDialog;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.yzdmw.toutiao.R;
import com.yzdmw.toutiao.databinding.CommentFragmentBinding;
import com.yzdmw.toutiao.databinding.LoginFragmentBinding;

import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.List;

public class CommentFragment extends Fragment {

    private CommentFragmentBinding binding;
    private CommentViewModel mViewModel;
    private ExpandableListView expandableListView;
    private CommentExpandAdapter adapter;
    private List<CommentViewModel.CommentDetailBean> commentsList;

    public static CommentFragment newInstance() {
        return new CommentFragment();
    }

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        binding = CommentFragmentBinding.inflate(getLayoutInflater());
        return binding.getRoot();
    }

    @Override
    public void onActivityCreated(@Nullable @org.jetbrains.annotations.Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
    }

    @Override
    public void onViewCreated(@NonNull @NotNull View view, @Nullable @org.jetbrains.annotations.Nullable Bundle savedInstanceState) {
        mViewModel = new ViewModelProvider(this).get(CommentViewModel.class);
        // TODO: Use the ViewModel
        expandableListView = this.getView().findViewById(R.id.detail_page_lv_comment);
        expandableListView.setGroupIndicator(null);
        mViewModel.init();
        commentsList = mViewModel.getCommentsList().getValue();
        adapter = new CommentExpandAdapter(this.getContext(), commentsList);
        expandableListView.setAdapter(adapter);
        mViewModel.getCommentsList().observe(getViewLifecycleOwner(), new Observer<List<CommentViewModel.CommentDetailBean>>() {
            @Override
            public void onChanged(@Nullable final List<CommentViewModel.CommentDetailBean> comment_list) {
                // Update the UI, in this case, a TextView.

            }
        });
        for(int i = 0; i < commentsList.size(); i++){
            expandableListView.expandGroup(i);
        }
        expandableListView.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
            @Override
            public boolean onGroupClick(ExpandableListView expandableListView, View view, int groupPosition, long l) {
                showReplyDialog(groupPosition, -1);
                return true;
            }
        });

        expandableListView.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
            @Override
            public boolean onChildClick(ExpandableListView expandableListView, View view, int groupPosition, int childPosition, long l) {
                showReplyDialog(groupPosition, childPosition);
                return false;
            }
        });

        FloatingActionButton addBtn = this.getView().findViewById(R.id.comment_button);
        addBtn.setOnClickListener(btn -> {
            showReplyDialog(-1, -1);
        });
    }

    private void showReplyDialog(int groupPosition, int childPosition){
        BottomSheetDialog dialog = new BottomSheetDialog(this.getContext());
        View commentView = LayoutInflater.from(this.getContext()).inflate(R.layout.comment_dialog_layout,null);
        final EditText commentText = (EditText) commentView.findViewById(R.id.dialog_comment_et);
        final Button bt_comment = (Button) commentView.findViewById(R.id.dialog_comment_bt);
        if(groupPosition != -1){
            if(childPosition != -1){
                commentText.setHint("回复 " + commentsList.get(groupPosition).getReplyList().get(childPosition).getNickName() + " 的评论:");
            }
            else{
                commentText.setHint("回复 " + commentsList.get(groupPosition).getNickName() + " 的评论:");
            }
        }
        else{
            commentText.setHint("编写评论");
        }
        dialog.setContentView(commentView);
        bt_comment.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String content = commentText.getText().toString().trim();
                if(!TextUtils.isEmpty(content)){
                    if(groupPosition != -1){
                        CommentViewModel.ReplyDetailBean detailBean;
                        if(childPosition != -1){
                            detailBean = new CommentViewModel.ReplyDetailBean(mViewModel.getmName(), content, commentsList.get(groupPosition).getReplyList().get(childPosition).getNickName());
                        }
                        else{
                            detailBean = new CommentViewModel.ReplyDetailBean(mViewModel.getmName(), content, null);
                        }
                        adapter.addTheReplyData(detailBean, groupPosition);
                    }
                    else{
                        CommentViewModel.CommentDetailBean detailBean = new CommentViewModel.CommentDetailBean(mViewModel.getmName(), 0, content, null);
                        adapter.addTheCommentData(detailBean);
                    }
                    Toast.makeText(getContext(),"回复成功", Toast.LENGTH_SHORT).show();
                    dialog.dismiss();
                }else {
                    Toast.makeText(getContext(),"回复内容不能为空", Toast.LENGTH_SHORT).show();
                }
            }
        });
        commentText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                if(!TextUtils.isEmpty(charSequence)){
                    bt_comment.setBackgroundColor(Color.parseColor("#6200EE"));
                }else {
                    bt_comment.setBackgroundColor(Color.parseColor("#D8D8D8"));
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        dialog.show();
    }

    public class CommentExpandAdapter extends BaseExpandableListAdapter {
        private static final String TAG = "CommentExpandAdapter";
        private List<CommentViewModel.CommentDetailBean> commentBeanList;
        private Context context;

        public CommentExpandAdapter(Context context, List<CommentViewModel.CommentDetailBean> commentBeanList)               {
            this.context = context;
            this.commentBeanList = commentBeanList;
        }

        @Override
        public int getGroupCount() {
            return commentBeanList.size();
        }

        @Override
        public int getChildrenCount(int i) {
                if(commentBeanList.get(i).getReplyList() == null){
                return 0;
            }else {
                return commentBeanList.get(i).getReplyList().size()>0 ? commentBeanList.get(i).getReplyList().size():0;
            }

        }

        @Override
        public Object getGroup(int i) {
            return commentBeanList.get(i);
        }

        @Override
        public Object getChild(int i, int i1) {
            return commentBeanList.get(i).getReplyList().get(i1);
        }

        @Override
        public long getGroupId(int groupPosition) {
            return groupPosition;
        }

        @Override
        public long getChildId(int groupPosition, int childPosition) {
            return getCombinedChildId(groupPosition, childPosition);
        }

        @Override
        public boolean hasStableIds() {
            return true;
        }

        @Override
        public View getGroupView(final int groupPosition, boolean isExpand, View convertView, ViewGroup viewGroup) {
            final GroupHolder groupHolder;

            if(convertView == null){
                convertView = LayoutInflater.from(context).inflate(R.layout.comment_item, viewGroup, false);
                groupHolder = new GroupHolder(convertView);
                convertView.setTag(groupHolder);
            }else {
                groupHolder = (GroupHolder) convertView.getTag();
            }
//            Glide.with(context).load(R.drawable.user_other)
//                    .diskCacheStrategy(DiskCacheStrategy.RESULT)
//                    .error(R.mipmap.ic_launcher)
//                    .centerCrop()
//                    .into(groupHolder.logo);
            CommentViewModel.CommentDetailBean comment = commentBeanList.get(groupPosition);
            groupHolder.tv_name.setText(comment.getNickName());
            groupHolder.tv_likeNum.setText("" + comment.getLikeNum());
            groupHolder.tv_content.setText(comment.getContent());
            if(!comment.getLike()){
                groupHolder.iv_like.setColorFilter(Color.parseColor("#aaaaaa"));
            }else {
                groupHolder.iv_like.setColorFilter(Color.parseColor("#FF5C5C"));
            }
            groupHolder.iv_like.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if(comment.getLike()){
                        comment.setLike(false);
                        comment.setLikeNum(comment.getLikeNum() - 1);
                        groupHolder.iv_like.setColorFilter(Color.parseColor("#aaaaaa"));
                    }else {
                        comment.setLike(true);
                        comment.setLikeNum(comment.getLikeNum() + 1);
                        groupHolder.iv_like.setColorFilter(Color.parseColor("#FF5C5C"));
                    }
                    groupHolder.tv_likeNum.setText("" + comment.getLikeNum());
                }
            });
            return convertView;
        }

        @Override
        public View getChildView(final int groupPosition, int childPosition, boolean b, View convertView, ViewGroup viewGroup) {
            final ChildHolder childHolder;
            if(convertView == null){
                convertView = LayoutInflater.from(context).inflate(R.layout.reply_item,viewGroup, false);
                childHolder = new ChildHolder(convertView);
                convertView.setTag(childHolder);
            }
            else {
                childHolder = (ChildHolder) convertView.getTag();
            }

            CommentViewModel.ReplyDetailBean replyUser = commentBeanList.get(groupPosition).getReplyList().get(childPosition);
            if(!TextUtils.isEmpty(replyUser.getNickName())){
                childHolder.tv_name.setText(replyUser.getNickName());
            }
            if(replyUser.getTo() != null && !TextUtils.isEmpty(replyUser.getTo())){
                childHolder.tv_to.setText(" @ " + replyUser.getTo());
            }

            childHolder.tv_content.setText(": " + commentBeanList.get(groupPosition).getReplyList().get(childPosition).getContent());

            return convertView;
        }

        @Override
        public boolean isChildSelectable(int i, int i1) {
            return true;
        }

        private class GroupHolder{
            private ImageView logo;
            private TextView tv_name, tv_content, tv_likeNum;
            private ImageView iv_like;
            public GroupHolder(View view) {
                logo =  view.findViewById(R.id.comment_ico);
                tv_content = view.findViewById(R.id.comment_data);
                tv_name = view.findViewById(R.id.comment_userName);
                iv_like = view.findViewById(R.id.comment_item_like);
                tv_likeNum = view.findViewById(R.id.like_num);
            }
        }

        private class ChildHolder{
            private TextView tv_name, tv_content,tv_to;
            public ChildHolder(View view) {
                tv_name = (TextView) view.findViewById(R.id.reply_userName);
                tv_content = (TextView) view.findViewById(R.id.reply_data);
                tv_to = (TextView) view.findViewById(R.id.reply_to);
            }
        }

        public void addTheCommentData(CommentViewModel.CommentDetailBean commentDetailBean){
            if(commentDetailBean!=null){
                commentBeanList.add(commentDetailBean);
                notifyDataSetChanged();
            }else {
                throw new IllegalArgumentException("评论数据为空!");
            }
        }

        public void addTheReplyData(CommentViewModel.ReplyDetailBean replyDetailBean, int groupPosition){
            if(replyDetailBean!=null){
                if(commentBeanList.get(groupPosition).getReplyList() != null ){
                    commentBeanList.get(groupPosition).getReplyList().add(replyDetailBean);
                }else {
                    List<CommentViewModel.ReplyDetailBean> replyList = new ArrayList<>();
                    replyList.add(replyDetailBean);
                    commentBeanList.get(groupPosition).setReplyList(replyList);
                }
                notifyDataSetChanged();
            }else {
                throw new IllegalArgumentException("回复数据为空!");
            }

        }

    }

}